#!/usr/bin/env python
#coding=utf8
# vim: set fileencoding=utf8 sts=4 sw=4 expandtab :
"""
 Copyright (C) 2008 Xupeng Yun <recordus@gmail.com>
 
 This file is part of videoapi. videoapi is a python lib/client for video sites such as www.tudou.com.

 Videoapi is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 
 Videoapi is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

 $Id:$
"""
import re
import os
import sys
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup

def read_url(url):
    headers = {'Referer' : 'http://www.tudou.com',
             'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'
      }
    req = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(req)
    html = response.read()
    return html

class TudouVideo:
    def __init__(self, url, title='', img=''):
        self.url = url
        self.img = img
        self.title = title

    def play(self):
        pass

    def toString(self):
        return '%s: %s' % (self.title, self.url)

    def toXML(self):
        return '<video img="%s" url="%s" title="%s" />' % (self.img,
                                                           self.url,
                                                           self.title
                                                          )

def get_flv_id(url):
    if 'iid=' in url:
        iid_re = re.compile('iid=(\d+)')
        _iid = iid_re.findall(url)
        iid = _iid and _iid[0] or None
    elif 'programs/view' in url:
        html = read_url(url)
        iid_re = re.compile('iid=(\d+)')
        _iid = iid_re.findall(html)
        iid = _iid and _iid[0] or None
    else:
        iid = None

    return iid

def get_flv_info_by_iid(iid):
    url = 'http://www.tudou.com/player/v.php?id=%s' % iid
    html = read_url(url)
    flv_urls = re.findall('http.*?\.flv', html)
    res = re.findall("q='(.*?)'", html)
    if res:
        title = res[0]
    else:
        title = 'Unknown'

    return {'title' : title, 'flv_urls' : flv_urls}

def get_flv_info_by_url(url):
    iid = get_flv_id(url)
    if iid:
        return get_flv_info_by_iid(iid)
    else:
        return {}

def play(url):
    flv_info = get_flv_info_by_url(url)
    if flv_info and flv_info.get('flv_urls', None):
        print flv_info['title']
        os.system('mplayer "%s"' % flv_info['flv_urls'][0])

def get_videos_from_serch_result(url):
    page_re = re.compile('page=(\d+)')
    current_page = page_re.findall(url) and page_re.findall(url)[0] or 1

    html = read_url(url)
    total_pages = page_re.findall(html) and page_re.findall(html) or []
    total_pages = [int(i) for i in total_pages]
    if total_pages:
        total_pages = max(total_pages)
    else:
        total_pages = 1 

    soup = BeautifulSoup(html)

    divImake = soup.find(attrs={'id' : 'searchContent'})
    imakes = divImake.findAll(attrs={'class' : 'in'})
    nextpage = soup.find(attrs={'class' : 'pagebarNext'})
    nexturl = ''
    if nextpage:
        nexturl = nextpage.find('a').get('href')
        if not nexturl.startswith('http://'):
            nexturl = 'http://so.tudou.com/%s' % nexturl
    prevpage = soup.find(attrs={'class' : 'pagebarPrv'})
    prevurl = ''
    if prevpage:
        prevurl = prevpage.find('a').get('href')
        if not prevurl.startswith('http://'):
            prevurl = 'http://so.tudou.com/%s' % prevurl
    videos = []
    count = 0 
    for imake in imakes:
        url_tag = imake.find('a')
        video_url = url_tag.get('href')
        img_tag = url_tag.find('img')
        img_url = img_tag.get('src')
        video_title = img_tag.get('alt')
        if video_title and ',' in video_title:
            video_title = ','.join(video_title.split(',')[:-1]).strip()

        video = TudouVideo(video_url, video_title, img_url)
        videos.append(video)
        count += 1

    #return output_xml(videos)
    print
    info = {
        'current_page' : current_page,
        'total_pages' : total_pages,
        'videos' : videos,
        'previous_url' : prevurl,
        'next_url' : nexturl,
    }
    return info

def print_menu(info):
    print 'Page: %s/%s' % (info['current_page'], info['total_pages'])
    count = 0
    videos = info['videos']
    for video in videos:
        print count, ':', video.title, video.url
        count += 1
    s = raw_input('Select: ')
    try:
        s = int(s)
    except:
        pass
    if type(s) == type(1):
        print videos[s].title, videos[s].url
        from tudou import play
        play(videos[s].url)
        print_menu(info)
    elif s == 'n':
        return info['next_url']
    elif s == 'p':
        return info['previous_url']
    elif s == 'q':
        sys.exit(1)


def search(kw):
    kw = urllib.quote(kw.decode(sys.stdin.encoding).encode('gbk'))
    url = 'http://so.tudou.com/isearch.do?kw=%s&row=30' % kw
    #url = 'http://so.tudou.com/isearch.do?                                   kw=%CF%EB%B0%AE%B6%BC%C4%D1&sort=date&rever=0&cid=0&isPublic=0&display=album&row=30'
    info = get_videos_from_serch_result(url)
    ret = print_menu(info)
    while info['next_url']:
        if ret:
            nexturl = ret
        else:
            nexturl = info['next_url']
        info = get_videos_from_serch_result(nexturl) 
        print_menu(info)

def main():
    #len(sys.argv) == 2 and play(sys.argv[1])
    #len(sys.argv) == 2 and search(sys.argv[1])
    if len(sys.argv) == 3:
        if sys.argv[1] == 'search':
            search(sys.argv[2])
        elif sys.argv[1] == 'play':
            play(sys.argv[2])

if __name__ == '__main__':
    main()
